﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication5.Feature;
using DBManager;
using RestSharp;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            var db = new PiiSDataModelContainer();
            var movieList = db.MovieSet.ToList();
            var featureList = db.FeatureSet.ToList();
            var restclient = new RestClient("http://api.themoviedb.org/3/");
            //var restrequest =
            //    new RestRequest("list/522effe419c2955e9922fcf3?api_key=d20b778e2233be6a4066a4e952164d2a", Method.GET);

            //var jsObject = restclient.Execute<JsonObject>(restrequest);

            //var sb = new StringBuilder();
            //var i = 1;
            //foreach (var movieItem in jsObject.Data.items)
            //{
            //    sb.Append("insert into [dbo].[MovieSet] values (" + i + "," + movieItem.id + ",\"" + movieItem.original_title + "\")\n");
            //    // sb.Append(i + ";" + movieItem.id  + ";" + movieItem.original_title + "\n");
            //    i++;
            //}

            //File.WriteAllText(@"d:\testing\movies.txt", sb.ToString());

            foreach (var movie in movieList)
            {
                var restrequest = new RestRequest("movie/" + movie.TMDBId + "?api_key=d20b778e2233be6a4066a4e952164d2a", Method.GET);
                var result = restclient.Execute<MovieJson>(restrequest);

                if (result.StatusCode != HttpStatusCode.OK)
                {
                    Console.WriteLine("========================================");
                    Console.WriteLine("Error while obtaining data for movie: " + movie.TMDBId);
                    Console.WriteLine("Status code: " + result.StatusCode + ", Response content: ");
                    Console.WriteLine(result.Content);
                    Console.WriteLine("========================================");
                    continue;
                }

                foreach (var feature in featureList)
                {
                    var dataObtainer = DataObtainerFactory.CreateDataObtainer(feature.Id, restclient);
                    try
                    {
                        string featureValue = dataObtainer.ObtainStringData(movie.TMDBId, result.Data);
                        var movieFeature = new Movies_Features { Value = featureValue, MovieId = movie.Id, FeatureId = feature.Id };
                        db.Movies_Features.Add(movieFeature);
                        //db.SaveChanges();
                    }
                    catch (NotImplementedException)
                    {
                        bool featureValue = dataObtainer.ObtainBoolData(movie.TMDBId, result.Data);
                        var movieFeature = new Movies_Features { Value = featureValue.ToString(), MovieId = movie.Id, FeatureId = feature.Id };
                        db.Movies_Features.Add(movieFeature);
                        //db.SaveChanges();
                    }
                    catch(System.Data.Entity.Validation.DbEntityValidationException)
                    {
                        
                    }
                }
            }


            //var lines = System.IO.File.ReadAllLines(@"D:\Dropbox\Public\movies.csv");
            //var sb = new StringBuilder();
            //foreach (var line in lines)
            //{
            //    var parts = line.Trim().Split(';');
            //    sb.AppendLine("insert into [dbo].[MovieSet] (Id, TMDBId, Title) values (" + parts[0] + "," + parts[1] + ",'" + parts[2] + "')");
            //}

            //System.IO.File.WriteAllText(@"d:\testing\movies.txt", sb.ToString());

            //var sb = new StringBuilder();

            //var personList = db.PersonSet.ToList();
            //var rand = new Random();

            //int evalCount = 0;
            //for (int i = 0; i < personList.Count; i++)
            //{
            //    var person = personList.ElementAt(i);
            //    var personId = i + 1;
            //    sb.AppendLine("INSERT INTO [dbo].[PersonSet] ([Id], [Description]) VALUES (" + personId + ", N'" + person.Description + "')");
            //    for (int j = 0; j < movieList.Count; j++)
            //    {
            //        var movie = movieList.ElementAt(j);
            //        var eval = person.Evaluation.Single(q => q.Movie == movie);
            //        evalCount++;
            //        var evalValue = eval.EvaluationValue == null ? "NULL" : eval.EvaluationValue.ToString();
            //        sb.AppendLine("INSERT INTO [dbo].[EvaluationSet] ([Id], [EvaluationValue], [MovieId], [PersonId]) VALUES (" + evalCount + ", " + evalValue + ", " + movie.Id + ", " + personId + ")");
            //    }
            //}

            //File.WriteAllText("script.sql", sb.ToString());

            ////for (int i = 0; i < 58; i++)
            ////{
            ////    var newPerson = new Person { Description = GetRandomPolishName() };
            ////    var person = personList.ElementAt(rand.Next(0, personList.Count));
            ////    foreach (var movie in movieList)
            ////    {
            ////        var evalVal = GetRandomEvaluation();
            ////        evalVal = evalVal == -1 ? person.Evaluation.Single(q => q.Movie == movie).EvaluationValue : evalVal;
            ////        var newEval = new Evaluation { Person = newPerson, Movie = movie, EvaluationValue = evalVal };
            ////        newPerson.Evaluation.Add(newEval);
            ////        Console.WriteLine("Added new eval to new person.");
            ////    }
            ////    personList.Add(newPerson);
            ////    db.PersonSet.Add(newPerson);
            ////    db.SaveChanges();
            ////    Console.WriteLine("Added new person to list.");

            ////}

            ////Console.WriteLine("Job done.");

            //var ppl = personList.Where(q => q.Evaluation.Count(w => w.EvaluationValue == null) == 200).ToArray();

            //var pplCount = ppl.Count();


            //for (int i = 0; i < pplCount; i++)
            //{
            //    var evalsCount = ppl[i].Evaluation.Count;
            //    for (int j = 0; j < evalsCount; j++)
            //    {
            //        db.EvaluationSet.Remove(ppl[i].Evaluation.First());
            //    }
            //    db.SaveChanges();
            //    db.PersonSet.Remove(ppl[i]);
            //    db.SaveChanges();
            //}



            //Console.WriteLine("Downloaded movie and person lists. Starting adding evals to exising ppl.");
            //foreach (var person in db.PersonSet)
            //{
            //    if(person.Evaluation.Count >= 200)
            //        continue;

            //    var movies = movieList.Where(q => person.Evaluation.Any(w => w.Movie == q) != true).ToList();
            //    foreach (var movie in movies)
            //    {
            //        var newEval = new Evaluation
            //                            {Person = person, Movie = movie, EvaluationValue = GetRandomEvaluation()};
            //        person.Evaluation.Add(newEval);
            //        Console.WriteLine("Added new eval to exisiting person.");
            //    }
            //}
            //db.SaveChanges();
            //Console.WriteLine("Finished adding evals to exisiting ppl. Starting with new ppl.");
            //while (personList.Count < 250)
            //{
            //    var newPerson = new Person {Description = GetRandomPolishName()};
            //    foreach (var movie in movieList)
            //    {
            //        var newEval = new Evaluation { Person = newPerson, Movie = movie, EvaluationValue = GetRandomEvaluation() };
            //        newPerson.Evaluation.Add(newEval);
            //        Console.WriteLine("Added new eval to new person.");
            //    }
            //    personList.Add(newPerson);
            //    Console.WriteLine("Added new person to list.");
            //}
            //Console.WriteLine("Finished adding ppl to list.");
            //db.SaveChanges();
            //Console.WriteLine("Changes saved.");
        }

        public static int? GetRandomEvaluation()
        {
            var rand = new Random();
            if (rand.Next(0, 10) <= 7)
            {
                return -1;
            }
            if (rand.Next(0, 10) < 5)
            {
                return null;
            }
            return rand.Next(2, 6);
        }

        public static string GetRandomPolishName()
        {
            var rand = new Random();
            var lines = File.ReadAllLines("imiona.csv").Select(a => a.Split(';')).ToArray();
            var name = lines[rand.Next(0, lines.Count())][0];
            return name.Substring(1, name.Length - 2);
        }
    }
}
